<?php

namespace App\Ad\Docking;

use App\Ad\MediaApi\MediaApiBase;
use App\Commons\CommonConstant;
use App\Datalog\AdMonitorLog;
use App\Models\AdMonitor;
use App\Models\AdPlan;
use App\Models\FirstupAd;
use App\Models\Log\LogAdMonitor;
use App\Models\Log\LogAdMonitorInfo;
use App\Models\Log\LogAdPostbackMedia;
use Illuminate\Http\Request;

// 快手-事件管理-小程序
class KuaishouMicroGame extends DockingBase
{
    // 点击监控参数
    protected $monitorParams = [
        'account_id'  => '__ACCOUNTID__',     // 广告账户ID
        'aid'         => '__AID__',           // 广告组ID
        'cid'         => '__CID__',           // 广告创意ID
        'did'         => '__DID__',           // 广告计划ID
        'dname'       => '__DNAME__',         // 广告计划名称
        'photoid'     => '__PHOTOID__',       // 素材ID
        'oaid2'       => '__OAID2__',         // Android	Android设备标识计算MD5
        'imei2'       => '__IMEI2__',         // Android	对15位数字的 IMEI
        'imei3'       => '__IMEI3__',         // Android	Android下的IMEI
        'imei4'       => '__IMEI4__',         // Android	IMEI进行 MD5
        'idfa2'       => '__IDFA2__',         // iOS下的idfa计算MD5
        'idfa3'       => '__IDFA3__',         // iOS下的idfa计算SHA1
        'kenyid_caa'  => '__KENYID_CAA__',    // iOS	URL Encode后的JSON数组
        'mac2'        => '__MAC2__',          // Android MAC 进行 MD5
        'mac3'        => '__MAC3__',          // Android MAC 去除分隔符之后进行 MD5
        'androidid2'  => '__ANDROIDID2__',    // ANDROIDID，原文计算MD5
        'androidid3'  => '__ANDROIDID3__',    // AndroidID，原文计算SHA1
        'ts'          => '__TS__',            // UTC时间戳
        'ua'          => '__UA__',            // 客户端UA
        'os'          => '__OS__',            // OS系统	1-iOS，0-安卓
        'model'       => '__MODEL__',         // 手机型号
        'callback'    => '__CALLBACK__',      // 回调信息
        'ip'          => '__IP__',            // ip地址
        'ipv4'        => '__IPV4__',          // IPV4地址
        'ipv6'        => '__IPV6__',          // IPV6地址
        'csite'       => '__CSITE__',         // 广告投放场景
        'ac_creative' => '__AC_CREATIVE__',   // 是否为高级创意	1：是
        'winfoid'     => '__WINFOID__',       // winfoid可通过marketing api 中关键词接口获得，对应word_info_id
        'llsid'       => '__LLSID__',         // 快手请求id
    ];

    // 转化类型映射
    protected $eventTypeMap = [
        CommonConstant::EVENT_FIRSTUP => 1,
        CommonConstant::EVENT_REG     => 2,
        CommonConstant::EVENT_PAY     => 3,
    ];

    // 此接口由子类继承
    // 获得点击监控链接拼接参数
    public function getMonitorParams($device_type): string
    {
        return http_build_query($this->monitorParams);
    }

    // 此接口由子类继承
    // 处理落地监控数据
    public function handleMonitorInfo(Request $request)
    {
        // 待匹配日志
        $params           = $request->all();
        $log              = LogAdMonitor::suffix(date('Ym'));
        $log->create_time = time();
        $log->plan_id     = $params['plan_id'];
        $log->ip          = $params['ip'] ?? '';
        $log->click_id    = md5($this->parseCallbackUrl($params['callback']));
        $log->save();

        // 完整日志
        $info              = LogAdMonitorInfo::suffix(date('Ym'));
        $info->create_time = time();
        $info->plan_id     = $params['plan_id'];
        $info->monitor_id  = $log->id;
        $info->data        = json_encode($params, JSON_UNESCAPED_UNICODE);
        $info->save();

        // 落地日志
        AdMonitorLog::getInstance()->addLog($log, $info);

        return yqok();
    }


    /**
     * 解析callback参数
     */
    public function parseCallbackUrl($callback)
    {
        $url = urldecode($callback);
        parse_str(parse_url($url, PHP_URL_QUERY), $query_arr);

        return $query_arr['callback'] ?? '';
    }

    /**
     * 此接口由子类继承
     * 根据媒体加密方式-生成对应的设备码，用于匹配
     * @param int      $device_type 设备类型
     * @param string[] $device_nums 设备码
     * @return array
     */
    public function getMonitorDeviceNum($device_type, $device_nums): array
    {
        $data = [];
        foreach ($device_nums as $key => $val) {
            switch ($key) {
                case 'click_id':
                    $data[$key] = $val;
                    break;
            }
        }

        return $data;
    }

    /**
     * 此接口由子类继承
     * 将用户行为进行api上报转化，如激活注册付费
     * 文档地址：https://docs.qingque.cn/d/home/eZQDnexll3-ebbtlX3xEDvBN3?identityId=1js2qROclGd#section=h.nxehxee2186m
     * @param int $event_type 事件类型 如激活注册付费
     * @param AdMonitor $monitor
     * @param FirstupAd $firstup_ad
     * @param mixed $mod 事件对应的模型 激活 Firstup 注册 Users 付费 Orders
     * @return int 处理结果状态
     */
    public function postbackToMedia($event_type, AdMonitor $monitor, FirstupAd $firstup_ad, $mod): int
    {
        // 此事件不需要上报
        if (!isset($this->eventTypeMap[$event_type])) {
            return LogAdPostbackMedia::STATUS_NONEED;
        }

        $plan = AdPlan::find($firstup_ad->plan_id);
        if ($plan['access_type'] != AdPlan::ACCESS_TYPE_API) {
            return LogAdPostbackMedia::STATUS_NOTAPI;
        }

        $monitor_data = json_decode($monitor->data, true);

        $params = [
            'callback'   => (string)$this->parseCallbackUrl($monitor_data['callback'] ?? ''),
            'event_type' => (int)$this->eventTypeMap[$event_type],
            'event_time' => intval(microtime(true) * 1000),
        ];

        if ($event_type == CommonConstant::EVENT_PAY) {
            $params['purchase_amount'] = round($mod->call_money, 2);
        }

        $url = 'http://ad.partner.gifshow.com/track/activate?' . http_build_query($params);

        $res = MediaApiBase::getInstance()->curl($url);
        if ($res[0] != 200) {
            return LogAdPostbackMedia::STATUS_FAIL;
        }

        $ret = json_decode($res[1], true);
        if (($ret['result'] ?? 0) != 1) {
            return LogAdPostbackMedia::STATUS_FAIL;
        }

        return LogAdPostbackMedia::STATUS_SUCC;
    }

    // 此接口由子类继承
    // 匹配成功后补齐监控数据
    public function supplementMonitorInfo(FirstupAd $firstup_ad, AdMonitor $monitor)
    {
        $data = json_decode($monitor->data, true);

        $firstup_ad->advertiser_id = intval($data['advertiser_id'] ?? 0);  // 广告主ID
        $firstup_ad->adgroup_id    = intval($data['did'] ?? 0);            // 广告计划ID 赋值到广告组ID
        $firstup_ad->ad_id         = intval($data['aid'] ?? 0);            // 广告组ID 赋值到广告ID
        $firstup_ad->adgroup_name  = $data['dname'] ?? '';                 // 广告计划名称
        $firstup_ad->creative_id   = intval($data['cid'] ?? 0);            // 广告创意ID
    }
}
